package com.ruoyi.function.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.RecognizeBusinessLicenseRequest;
import com.aliyun.ocr_api20210707.models.RecognizeBusinessLicenseResponse;
import com.aliyun.ocr_api20210707.models.VerifyBusinessLicenseRequest;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.function.domain.Garage;
import com.ruoyi.function.mapper.GarageMapper;
import com.ruoyi.function.service.BusinessLicenseService;
import com.ruoyi.function.service.FileUploadService;
import com.ruoyi.function.utility.AliyunConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BusinessLicenseServiceImpl implements BusinessLicenseService {
    
    private static final Logger log = LoggerFactory.getLogger(BusinessLicenseServiceImpl.class);

    @Autowired
    private AliyunConfig aliyunConfig;

    @Autowired
    private GarageMapper garageMapper;

    @Autowired
    private FileUploadService fileUploadService;  // 注入文件上传服务

    /**
     * 营业执照识别并核验
     */
    @Override
    @Transactional
    public Object recognizeBusinessLicense(InputStream inputStream, Long userId) throws Exception {
        try {
            // 创建OCR客户端
            Config config = new Config()
                .setAccessKeyId(aliyunConfig.getAccessKeyId())
                .setAccessKeySecret(aliyunConfig.getAccessKeySecret());
            config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
            Client client = new Client(config);

            // 1. OCR识别
            RecognizeBusinessLicenseRequest request = new RecognizeBusinessLicenseRequest();
            request.setBody(inputStream);
            RuntimeOptions runtime = new RuntimeOptions();

            RecognizeBusinessLicenseResponse response = client.recognizeBusinessLicenseWithOptions(request, runtime);
            
            // 打印OCR识别结果
            log.info("营业执照OCR识别结果: {}", response.getBody().getData());
            
            JSONObject rawData = JSONObject.parseObject(response.getBody().getData());
            JSONObject data = rawData.getJSONObject("data");  // 注意这里，需要先获取data对象
            
            if (data == null) {
                log.error("OCR识别结果中没有data字段");
                throw new ServiceException("营业执照识别失败");
            }
            
            // 2. 提取关键信息 - 使用正确的字段名
            String creditCode = data.getString("creditCode");         // 统一社会信用代码
            String companyName = data.getString("companyName");      // 企业名称
            String legalPerson = data.getString("legalPerson");      // 法人姓名
            
            log.info("提取的营业执照信息 - 统一社会信用代码: {}, 企业名称: {}, 法人: {}", 
                creditCode, companyName, legalPerson);

            // 3. 进行核验
            boolean verifyResult = verifyBusinessLicense(creditCode, companyName, legalPerson);
            
//            // 4. 更新商家信息
//            if (verifyResult) {
//                Garage garageInfo = garageMapper.selectByUserId(userId);
//                if (garageInfo != null) {
//                    // 获取现有的营业执照图片列表
//                    List<String> existingLicenses = new ArrayList<>();
//                    if (StringUtils.hasText(garageInfo.getBusinessLicense())) {
//                        existingLicenses = JSONObject.parseArray(garageInfo.getBusinessLicense(), String.class);
//                    }
//
//                    garageInfo.setCompanyName(companyName);
//                    garageInfo.setCreditCode(creditCode);
//                    garageInfo.setLegalPerson(legalPerson);
//                    garageInfo.setBusinessLicenseStatus(1);  // 1-验证通过
//                    garageInfo.setBusinessLicenseRemark("验证通过");
//                    garageMapper.updateGarage(garageInfo);
//                }
//            } else {
//                log.warn("营业执照核验未通过 - userId: {}, creditCode: {}", userId, creditCode);
//            }

            // 5. 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("ocrData", data);
            result.put("verifyResult", verifyResult);
            return result;

        } catch (Exception e) {
            log.error("营业执照处理异常", e);
            throw e;
        }
    }

    /**
     * 营业执照三要素核验
     */
    private boolean verifyBusinessLicense(String creditCode, String companyName, String legalPerson) {
        try {
            // 参数校验
            if (!StringUtils.hasText(creditCode) || !StringUtils.hasText(companyName) || !StringUtils.hasText(legalPerson)) {
                log.warn("营业执照信息不完整 - creditCode: {}, companyName: {}, legalPerson: {}", 
                    creditCode, companyName, legalPerson);
                return false;
            }

            // 创建核验客户端
            Config config = new Config()
                .setAccessKeyId(aliyunConfig.getAccessKeyId())
                .setAccessKeySecret(aliyunConfig.getAccessKeySecret());
            config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
            Client client = new Client(config);

            // 创建核验请求
            VerifyBusinessLicenseRequest request = new VerifyBusinessLicenseRequest()
                .setCreditCode(creditCode)
                .setCompanyName(companyName)
                .setLegalPerson(legalPerson);

            // 打印请求参数
            log.info("发送营业执照核验请求 - 参数: {}", JSONObject.toJSONString(request));

            // 发送请求
            RuntimeOptions runtime = new RuntimeOptions();
            com.aliyun.ocr_api20210707.models.VerifyBusinessLicenseResponse response = 
                client.verifyBusinessLicenseWithOptions(request, runtime);

            // 打印原始响应
            log.info("营业执照核验原始响应: {}", JSONObject.toJSONString(response));

            // 解析结果
            JSONObject verifyData = JSONObject.parseObject(response.getBody().getData());
            String code = verifyData.getString("code");
            boolean isMatch = verifyData.getBooleanValue("data");
            
            log.info("营业执照核验结果 - code: {}, isMatch: {}, message: {}", 
                code, isMatch, verifyData.getString("message"));
                
            return "0".equals(code) && isMatch;

        } catch (Exception e) {
            log.error("营业执照核验异常", e);
            return false;
        }
    }
} 